import React from 'react';
import get from 'lodash/get';
import PropTypes from 'prop-types';
import moment from 'moment-timezone';
import { FormattedMessage, injectIntl } from 'react-intl';
import { stripesConnect, IfPermission } from '@folio/stripes/core';
import {
  StripesConnectedSource
} from '@folio/stripes/smart-components';
import {
  Row,
  Col,
  ButtonGroup,
  Button,
  MultiColumnList,
  Checkbox,
  Field,
  Select
} from '@folio/stripes/components';
import { examineState, attendanceState } from '../../components/party-attend/enum';
import SearchForm from '../../components/party-attend/search-form';
import SupplementForm from '../../components/party-attend/supplement-form';
import css from '../../components/party-attend/style.css';
import ExprotExcel from '../../util/ExportExcel';

const defaultParser = (value, timeZone, dateFormat) => {
  if (!value || value === '') { return value; }

  const offsetRegex = /T[\d.:]+[+-][\d]+$/;
  let inputMoment;
  // if date string contains a utc offset, we can parse it as utc time and convert it to selected timezone.
  if (offsetRegex.test(value)) {
    inputMoment = moment.tz(value, timeZone);
  } else {
    inputMoment = moment.tz(value, dateFormat, timeZone);
  }
  const inputValue = inputMoment.format(dateFormat);
  return inputValue;
};

class List extends React.Component {
  static manifest = Object.freeze({
    deleteId: { initialValue: '' },
    attendQuery: { initialValue: '' },
    resultCount: { initialValue: 10 },
    recordsRecords: {
      type: 'okapi',
      path: 'party/attend',
      recordsRequired: '%{resultCount}',
      // accumulate: true,
      perRequest: 10,
      limitParam: 'limit',
      records: 'attendGroup',
      GET: {
        params: {
          query: '(isDel = 0 ${attendQuery}) sortby reserveDate/sort.descending '
        }
      }
    },
    userNames: {
      type:'okapi',
      path: 'party/users',
      accumulate: true,
      fetch: false
    },
    activityNames: {
      type:'okapi',
      path: 'activity/signIn/getActivityNames',
      accumulate: true,
      fetch: false
    },
    read: {
      type:'okapi',
      path: 'activity/signIn/read',
      fetch: false
    },
    delete: {
      type:'okapi',
      path: 'activity/signIn/delete/%{deleteId}',
      fetch: false
    },
    batchAttendance: {
      type:'okapi',
      path: 'party/attend/attend_batch_update',
      fetch: false
    },
    getActivityList: {
      type: 'okapi',
      accumulate: true,
      path: 'party/info',
      records: 'partyGroup',
      perRequest: 10,
      limitParam: 'size',
      GET: {
        params: {
          query: '(isDel = 0)'
        }
      }
    },
  })

  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({
      deleteId: PropTypes.string,
      attendQuery: PropTypes.string,
      recordsRecords:{
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      },
      batchAttendance: PropTypes.shape({
        POST: PropTypes.func.isRequired,
        PUT: PropTypes.func.isRequired,
      }),
      getActivityList:PropTypes.shape({
        GET: PropTypes.func.isRequired,

      })
    }).isRequired,
    dictionary: PropTypes.object,
    okapi:PropTypes.object
  }

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      operator:{},
      searchFlag:true,
      searchForm: {
        jsonb:{ name: '' },
        query: {
          data: {
            start: {
              activityTime:''
            },
            end: {
              activityTime:''
            }
          }
        }

      },
      supplementForm: {
        partyName: '',
        partyId: '',
        readId: '',
        attendState: ''
      },
      isOpen: false,
      msg:'',
      isAllChecked: false,
      checkedState: {},
      selected: [],
      attendance: null,
      userNames: [],
      activityNames: [],
      addModal:''
    };
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
    // this.getActivityNames();
    // this.getUserNames();
    // this.getDataList();

    const { currentUser } = this.props.okapi;
    if (currentUser) {
      this.setState({
        operator: currentUser
      });
    }
  }

  componentDidUpdate() {
    this.source.update(this.props);
  }

  componentWillUnmount() {
    const {
      mutator
    } = this.props;
    mutator.attendQuery.replace('');
  }

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(10);
    }
  }

  deleteDate = (id) => {
    const {
      mutator
    } = this.props;
    mutator.deleteId.replace(id);
    mutator.delete.DELETE({ params:{ id } }).then(() => {
      mutator.deleteId.replace('');
    });
  }

  batchAttendance = () => {
    const {
      mutator,
      intl
    } = this.props;
    if (!this.state.selected || this.state.selected.length === 0) {
      alert(intl.formatMessage({ id:'ui-party.errors.message.party.select.data' }));
      return;
    }
    if (!this.state.attendance) {
      alert('请选择考勤状态');
      return;
    }
    const idArray = this.state.selected.toString();

    const data = {
      idArray,
      attendState:this.state.attendance,
      operator:this.state.operator
    };
    delete data.operator.addresses;
    delete data.operator.preferredContactTypeId;
    delete data.operator.servicePoints;
    delete data.operator.curServicePoint;
    delete data.operator.dateOfBirth;
    // mutator.batchAttendance.POST(json).then(res=>{
    //
    // });
    const attendState = this.state.attendance;
    // let idList= idArray.split(",");
    //   for (let i = 0; i < idList.length; i++) {
    //      let id=idList[i];
    //      let param = {
    //          id,
    //          attendState
    //      }
    mutator.recordsRecords.POST(data);
    // }
  }

  batchAttendanceChange = (e) => {
    const select = e.currentTarget;
    this.setState({
      attendance: select.value
    });
  }

  search = ({ requestPreferences, creds, ...formData }) => {
    const {
      mutator,

    } = this.props;
    let query = '';
    if (!!formData.partyEndDate && !formData.partyStartDate) {
      const temp = defaultParser(formData.partyEndDate, 'Asia/Shanghai', 'YYYY-MM-DD');
      query += ` and partyEndDate >= "${temp} 00:00:00" and partyEndDate <= "${temp} 23:59:59" `;
    }
    if (!!formData.partyStartDate && !formData.partyEndDate) {
      const temp = defaultParser(formData.partyStartDate, 'Asia/Shanghai', 'YYYY-MM-DD');
      query += ` and partyStartDate >= "${temp} 00:00:00" and partyStartDate <= "${temp} 23:59:59" `;
    }
    if (!!formData.partyStartDate && !!formData.partyEndDate) {
      const tempEndDate = defaultParser(formData.partyEndDate, 'Asia/Shanghai', 'YYYY-MM-DD');
      const tempStartDate = defaultParser(formData.partyStartDate, 'Asia/Shanghai', 'YYYY-MM-DD');
      query += ` and partyStartDate >= "${tempStartDate} 00:00:00" and partyEndDate <= "${tempEndDate} 23:59:59" `;
    }
    if (formData.partyName) {
      query += ` and partyName = ${formData.partyName}*`;
    }
    if (formData.name) {
      query += ` and readerReserveGroup == *"name"*: *"${formData.name}"* `;
    }
    if (formData.attendState) {
      query += ` and attendState == ${formData.attendState}`;
    }

    mutator.attendQuery.replace(query);
    if (this.source && this.state.searchFlag) {
      this.source.update(this.props);
      this.setState({ searchForm:formData, searchFlag : false }, () => {
        setTimeout(() => {
          this.setState({
            searchFlag:true
          });
        }, 500);
      });
    }
  }

  cleanSearch = () => {
    const {
      mutator
    } = this.props;
    this.setState({
      searchForm: {
        jsonb:{ name: '' },
        attendQuery: {
          data: {
            start: {
              activityTime:''
            },
            end: {
              activityTime:''
            }
          }
        }
      }
    });
    this.searchFromRef.clearDate();
    mutator.attendQuery.replace('');
    if (this.source) {
      this.source.update(this.props);
    }
  }

  export = () => {
    const {
      okapi,

    } = this.props;

    const token = okapi.token;
    const tenant = okapi.tenant;

    const params = this.state.searchForm;
    const p = params;
    let query = '';
    if (this.state.selected.length > 0) {
      this.state.selected.forEach((a) => {
        query += ` id = ${a} or`;
      });
      const idParams = ` query=(${query.slice(0, query.length - 3)})`;
      query = idParams;
    }

    const path = okapi.url + '/party/attend/to/export_excel';
    const requestParams = query;
    const fileName = '读者考勤统计';
    const type = 'GET';
    ExprotExcel.exprot(
      path,
      requestParams,
      type,
      fileName,
      token,
      tenant
    );
  }

  supplementSignIn = ({ requestPreferences, creds, ...formData }) => {
    const {
      mutator,
        intl
    } = this.props;
    this.setState({
      msg: ''
    });

    if (!formData.readId) {
      return false;
    }
    this.getUserNames(formData.readId).then(res => {
      const group = res.users;
      let user = null;
      group.forEach(a => {
        if (a.barcode === formData.readId) {
          user = a;
        }
      });
      if (!user) {
        alert( intl.formatMessage({id:"ui-party.other.reader.isnull"}));
        return false;
      } else {
        const param = {
          readId: user.barcode,
          readerReserveGroup:
                  [
                    {
                      name:user.username,
                      barcode:user.barcode,
                      mobilePhone: user.personal.mobilePhone
                    }
                  ],
          propertyName:formData.propertyName,
          partyId: formData.partyId,
          partyName: formData.partyName,
          partyStartDate:formData.partyStartDate,
          state: 1,
          attendState:formData.attendState,
          isDel:0,
          operator:this.state.operator
        };

        mutator.recordsRecords.POST(param).then(res => {
          // this.setState({ isOpen: false });
          alert(intl.formatMessage({id:"ui-party.other.saved.successfully"}));
        });
      }
    });

  }

  setSupplementForm = (activityName, activityId, readId, attendanceState) => {
    this.setState((prevState) => {
      const json = prevState.supplementForm;
      json.activityName = activityName;
      json.activityId = activityId;
      return {
        supplementForm:json
      };
    });
  }

  getActivityList = (activityName) => {
    const {
      mutator
    } = this.props;
    const params = {

      query:' isDel = 0 '

    };

    if (activityName) {
      const tmp = `and partyName == *${activityName}*`;
      params.query += tmp;
    }

    mutator.getActivityList.GET({ params });
  }

  searchFromRef = (ref) => {
    this.searchFromRef = ref;
  }

  supplementFormRef = (ref) => {
    this.supplementFormRef = ref;
  }

  rowClick = (e, item) => {
    this.setState(prevState => {
      const selectedArray = prevState.selected;
      if (selectedArray.indexOf(item.id) > -1) {
        selectedArray.splice(selectedArray.indexOf(item.id), 1);
      } else {
        selectedArray.push(item.id);
      }
      return {
        isAllChecked: false,
        selected: selectedArray
      };
    });
  }

  checkChange = (e) => {
    const input = e.currentTarget;
    this.setState(prevState => {
      const selectedArray = prevState.selected;
      const checkedState = prevState.checkedState;
      if (input.checked) {
        selectedArray.push(input.value);
        checkedState[input.value] = true;
      } else {
        selectedArray.splice(selectedArray.indexOf(input.value), 1);
        checkedState[input.value] = false;
      }
      return {
        isAllChecked: false,
        selected: selectedArray,
        checkedState
      };
    });
  }

  allCheckToggle = () => {
    const {
      resources
    } = this.props;
    this.setState((prevState) => {
      const dataList = get(resources, 'recordsRecords.records', []);
      const selectedArray = [];
      const checkedState = prevState.checkedState;
      if (!prevState.isAllChecked) {
        dataList.forEach((value, index) => {
          selectedArray.push(value.id);
          checkedState[value.id] = true;
        });
        return { selected:selectedArray, isAllChecked:true, checkedState };
      } else {
        dataList.forEach((value, index) => {
          checkedState[value.id] = false;
        });
        return { selected:selectedArray, isAllChecked:false, checkedState };
      }
    });
  }

  getUserNames = (readerId) => {
    const {
      mutator
    } = this.props;
    const params = {
      params: {
        query:readerId
      }
    };
    return mutator.userNames.GET(params);
  }

  getActivityNames = () => {
    const {
      mutator
    } = this.props;
    const params = {
      params: {
      }
    };
 
    return mutator.activityNames.GET(params);
  }

  openAddModal=(flag = false) => {
    if (flag) {
      this.setState((prevState) => {
        const addModal = <SupplementForm handleCancel={this.openAddModal} operator={prevState.operator} />;
        return {
          addModal
        };
      });
    } else {
      this.setState({
        addModal:''
      });
    }
  }

  render() {
    const {
      resources,

    } = this.props;
    if (this.source) {
      this.source.update(this.props);
    }
    const totalCount = this.source ? this.source.totalCount() : 0;
    const dataList = get(resources, 'recordsRecords.records', []);
    const attendanceStateOptions = (attendanceState || []).map(g => {
      return (
        <FormattedMessage key={g.id} id={g.desc}>
          {(message) => <option value={g.id}>{message}</option>}
        </FormattedMessage>
      );
    });
  


    const resultsFormatter = {
      checkBox: item => {
        return (
          <Checkbox name="selectList" checked={this.state.checkedState[item.id]} onClick={this.checkChange} value={item.id} />
        );
      },
      activityName: item => {
        return (
          <span
            style={
              {
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                wordBreak: 'break-all'
              }
            }
            title={item.partyName}
          >
            {item.partyName}
          </span>
        );
      },
      readName: item => `${item.readerReserveGroup[0].name}`,
    
      attendanceState: item => {
        // return <div>{item.attendState}</div>
        const attendanceStateObject = (attendanceState || {}).find(t => (t.id === item.attendState));
        return (
          <FormattedMessage id={(attendanceStateObject || {}).desc || 'ui-party.empty'} />
        );
      },
      registerTime: item => {
        if (item.reserveDate) {
          return defaultParser(item.reserveDate, 'UTC', 'YYYY-MM-DD HH:mm');
          // return item.reserveDate
        } else {
          return '';
        }
      },
      activityTime: item => {
        return defaultParser(item.partyStartDate, 'UTC', 'YYYY-MM-DD HH:mm');
      }
    };
    return (
      <div>
        {this.state.addModal}
        <SearchForm
          getActivityNames={this.getActivityNames}
          getUserNames={this.getUserNames}
          onSubmit={this.search}
          initialValues={this.state.searchForm}
          cleanSearch={this.cleanSearch}
          onRef={this.searchFromRef}
          {...this.props}
        />
        <Row>
          <Col className={css.inputCalss}>
            <ButtonGroup>
              {/* <Button><Link to="/activity/signIn/add">新增</Link></Button> */}

              <IfPermission perm="ui-party.attend.manage.view.add">
                <Button onClick={() => {
                  this.openAddModal(true);
                }}
                >
                  <FormattedMessage id="ui-party.attend.operating.install.data" />
                </Button>
              </IfPermission>
              <IfPermission perm="ui-party.attend.manage.view.export">
                <Button onClick={this.export}>
                  <FormattedMessage id="ui-party.export" />
                </Button>
              </IfPermission>
            </ButtonGroup>
          </Col>
          <IfPermission perm="ui-party.attend.manage.view.modify">
            <Col className={css.inputCalss}>
              <Row className={css.inputCalss}>
                <Col>
                  <Select
                    selectClass={css.selectWidth}
                    onChange={this.batchAttendanceChange}
                  >
                    {attendanceStateOptions}
                  </Select>
                </Col>
                <Col className={css.inputCalss}>
                  <Button onClick={this.batchAttendance}>
                    <FormattedMessage id="ui-party.attend.operating.batch.verify" />
                  </Button>
                </Col>
              </Row>
            </Col>
          </IfPermission>
        </Row>
        <MultiColumnList
          // onRowClick={this.rowClick}
          height={500}
          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          // pagingType="click"
          totalCount={totalCount}
          virtualize
          contentData={dataList}
          onNeedMoreData={this.moreData}
          formatter={resultsFormatter}
          visibleColumns={['checkBox', 'activityName', 'readName' , 'attendanceState', 'registerTime', 'activityTime']}
          columnMapping={{
            checkBox: <Checkbox checked={this.state.isAllChecked} onChange={this.allCheckToggle} />,
            activityName: <FormattedMessage id="ui-party.loans.columns.party.partyName" />,
            readName: <FormattedMessage id="ui-party.loans.columns.readerName" />,
            
            attendanceState: <FormattedMessage id="ui-party.loans.columns.party.attendStatus" />,
            registerTime: <FormattedMessage id="ui-party.loans.columns.party.reserveDate" />,
            activityTime: <FormattedMessage id="ui-party.loans.columns.party.partyDate" />,

          }}
          columnWidths={{
            checkBox: '5%',
            activityName: '20%',
            readName: '20%',
            examineState: '10%',
            attendanceState: '10%',
            registerTime: '15%',
            activityTime: '15%',
            // operation: '15%'
          }}
        />
      </div>
    );
  }
}
export default stripesConnect(injectIntl(List));
